package com.secxiot.common.converter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class DateConverter implements Converter<String, Date> {

    private static SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    private static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public Date convert(String source) {
        if ("".equals(source) || source == null) {
            return null;
        }
        try {
            return sdf2.parse(source);
        } catch (ParseException e) {
            try {
                Date date = new Date(Long.parseLong(source));
                return date;
            } catch (NumberFormatException ex) {
                log.error("日期转换错误,source:" + source, ex);
            }
        }
        return null;
    }
}
